<template>
    <div class="ai-container">
        <!-- 背景装饰 (来自 HomeView) -->
        <div class="medical-bg"></div>

        <!-- 头部 (固定顶部栏) -->
        <header class="app-header">
            <button class="back-button" @click="goBack" title="返回">
                <i class="fas fa-arrow-left"></i>
            </button>
            <div class="header-content">
                <h1>AI智能问诊</h1>
            </div>
            <div class="header-placeholder"></div> <!-- Matched placeholder -->
        </header>

        <!-- 新增：指标按钮行 -->
        <div class="metric-buttons">
            <button 
                v-for="metric in metrics" 
                :key="metric.key"
                :class="['metric-button', { active: selectedMetric === metric.key }]"
                @click="selectMetric(metric.key)"
            >
                {{ metric.label }}
            </button>
        </div>

        <!-- 主要内容区域 -->
        <div class="ai-content">
            <!-- 聊天容器 -->
            <div class="chat-container">
                <div class="messages" ref="messageContainer">
                    <div v-for="(msg, index) in messages" :key="index" 
                         :class="['message', msg.role]">
                        <!-- Avatar -->
                        <div class="avatar">
                            <i v-if="msg.role === 'assistant'" class="fas fa-robot"></i>
                            <i v-else class="fas fa-user"></i>
                        </div>
                        <!-- Bubble -->
                        <div class="bubble">{{ msg.content }}</div>
                    </div>
                    <!-- 加载指示器 -->
                    <div v-if="loading" class="loading">
                        <div class="loading-dots">
                            <span></span>
                            <span></span>
                            <span></span>
                        </div>
                        <p>思考中...</p>
                    </div>
                </div>

                <!-- 输入区域 -->
                <div class="input-area">
                    <div class="input-group">
                        <i class="fas fa-comment-dots input-icon"></i> <!-- 可选：输入图标 -->
                        <input 
                            v-model="inputMessage" 
                            @keyup.enter="sendMessage"
                            placeholder="描述您的症状或问题..."
                            type="text"
                            class="chat-input"
                        >
                        <!-- 语音输入按钮 -->
                        <button 
                            class="voice-button" 
                            @click="toggleVoiceInput"
                            :class="{ 'active': isRecognizing }"
                            title="语音输入"
                        >
                            <i class="fas fa-microphone"></i>
                        </button>
                    </div>
                    <!-- 发送按钮 -->
                    <button 
                        class="send-button" 
                        @click="sendMessage" 
                        title="发送"
                        :disabled="loading" 
                    >
                        <i class="fas fa-paper-plane"></i>
                    </button>
                </div>
            </div>
        </div>

        <!-- 底部导航组件 -->
        <navigation :active-tab="activeTab" @tab-change="handleTabChange" />
    </div>
</template>

<script>
import { ref, onMounted, nextTick } from 'vue';
import { useRouter } from "vue-router";
import Navigation from '@/components/Navigation.vue'; // Import Navigation component
import axios from 'axios';
import { getItem } from '@/components/Session.vue';

export default {
    components: { // 注册导航组件
        Navigation
    },
    setup() {
        const router = useRouter();
        const activeTab = ref('ai'); // 设置初始活动标签（可以是 'home' 或像 'ai' 这样的新标签）
        const inputMessage = ref('');
        const messages = ref([
            { role: 'assistant', content: '您好！我是您的AI健康助手，请描述您的症状或健康问题。' } // 更新后的初始消息
        ]);
        const loading = ref(false);
        const isRecognizing = ref(false);
        const messageContainer = ref(null);
        let ws = null; // 全局WebSocket连接

        // 新增：指标按钮相关状态和数据
        const metrics = ref([
            { key: 'temperature', label: '体温' },
            { key: 'bloodPressure', label: '血压' },
            { key: 'bloodSugar', label: '血氧' },
            { key: 'heartRate', label: '心率' }
        ]);
        const selectedMetric = ref('bloodPressure'); // 默认选中'血压'

        // 新增：选择指标按钮的函数
        const selectMetric = async (metricKey) => {
            selectedMetric.value = metricKey;
            const user = getItem('user');
            const metricLabel = metrics.value.find(metric => metric.key === metricKey)?.label;
            loading.value = true; // 显示加载状态
            try {
                const response = await axios.get(`/api/chat/getSuggestInWebsocket?username=${user.username}&indicatorName=${encodeURIComponent(metricLabel)}`);
                if (response.data.code !== 200) {
                    messages.value.push({ role: 'assistant', content: `错误：${response.data.message}` });
                }
            } catch (error) {
                console.error('获取建议失败:', error);
                messages.value.push({ role: 'assistant', content: '获取建议时出错，请稍后再试。' });
            } finally {
                loading.value = false; // 隐藏加载状态
            }
        };

        // 更新后的发送消息函数
        const sendMessage = async () => {
            const messageContent = inputMessage.value.trim();
            if (!messageContent) return;

            // 1. 添加用户消息到列表
            messages.value.push({ role: 'user', content: messageContent });
            inputMessage.value = ''; // 清空输入框
            await scrollToBottom();

            // 2. 显示加载状态
            loading.value = true;

            // 3. 通过WebSocket发送消息
            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.send(messageContent);
            } else {
                // 如果WebSocket未连接，尝试重新连接
                connectWebSocket();
                messages.value.push({ role: 'assistant', content: '连接已断开，正在重新连接...' });
                loading.value = false;
                scrollToBottom();
            }
        };
        
        // 滚动到底部（保留现有逻辑）
        const scrollToBottom = async () => {
            await nextTick();
            if (messageContainer.value) {
                messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
            }
        };
        
        // 切换语音输入（保留现有逻辑）
        const toggleVoiceInput = () => {
            isRecognizing.value = !isRecognizing.value;
            // 在此处添加实际的语音识别逻辑
            console.log(isRecognizing.value ? '开始语音' : '停止语音');
        };
        
        // 处理来自导航组件的标签更改
        const handleTabChange = (newTab) => {
            activeTab.value = newTab;
            if (newTab === 'home') {
                router.push('/'); // Changed from /index to /
            } else if (newTab === 'mine') {
                router.push('/personal');
            }
            // 如果需要，添加其他标签
        };
        
        // 返回上一页或主页 (Matched Family.vue)
        const goBack = () => {
             if (window.history.length > 1) {
                 router.go(-1);
             } else {
                 router.push('/');
             }
        };
        
        // 连接WebSocket的函数
        const connectWebSocket = () => {
            const user = getItem('user');
            if (!user || !user.username) {
                console.error('用户信息获取失败，无法连接WebSocket');
                return;
            }
            
            // 如果已有连接，先关闭
            if (ws) {
                ws.close();
            }
            
            // 创建新连接
            ws = new WebSocket(`ws://47.111.115.11:8080/chat/ai/${user.username}`);
            
            ws.onopen = () => {
                console.log('WebSocket连接已建立');
            };
            
            ws.onmessage = (event) => {
                // 添加 AI 回复到列表
                messages.value.push({ role: 'assistant', content: event.data });
                loading.value = false;
                scrollToBottom();
            };
            
            ws.onerror = (error) => {
                console.error('WebSocket错误:', error);
                messages.value.push({ role: 'assistant', content: '连接出错，请稍后再试。' });
                loading.value = false;
                scrollToBottom();
            };
            
            ws.onclose = () => {
                console.log('WebSocket连接已关闭');
                // 可以在这里添加重连逻辑
                setTimeout(() => {
                    if (ws.readyState === WebSocket.CLOSED) {
                        connectWebSocket();
                    }
                }, 5000); // 5秒后尝试重连
            };
        };
        
        onMounted(() => {
            // 页面加载时连接WebSocket
            connectWebSocket();
            scrollToBottom();
        });
        
        return {
            activeTab,
            inputMessage,
            messages,
            loading,
            isRecognizing,
            messageContainer,
            metrics, // 暴露指标数据
            selectedMetric, // 暴露当前选中的指标
            sendMessage,
            toggleVoiceInput,
            selectMetric, // 暴露选择指标的方法
            handleTabChange,
            goBack
        };
    }
}
</script>

<style scoped>
.ai-container {
    height: 100vh; /* Full viewport height */
    display: flex;
    flex-direction: column;
    background: #f8f9fa; /* Match LoginView background */
    position: relative;
    font-family: 'Inter', 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
    /* Keep padding-bottom ONLY if Navigation component is truly position:fixed */
    padding-bottom: 60px; /* Adjust this value based on actual Navigation height */
    overflow: hidden; /* Prevent the whole container from scrolling */
}

/* Background Decoration (Match LoginView) */
.medical-bg {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: 
        linear-gradient(135deg, rgba(76, 175, 80, 0.03) 0%, rgba(33, 150, 243, 0.03) 100%); /* Use theme colors subtly */
    z-index: 0;
}

.medical-bg::before,
.medical-bg::after {
    content: '';
    position: absolute;
    width: 200px;
    height: 200px;
    border-radius: 50%;
    background: rgba(33, 150, 243, 0.02); /* Use theme color subtly */
}

.medical-bg::before {
    top: -50px;
    right: -50px;
}

.medical-bg::after {
    bottom: -50px;
    left: -50px;
}

/* Header (Matched Family.vue) */
.app-header {
    background: linear-gradient(135deg, #4CAF50, #2196F3); /* Matched gradient */
    color: white; /* Matched text color */
    padding: 4vw; /* Matched padding */
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: sticky; /* Keep sticky */
    top: 0;
    z-index: 100;
    /* Removed fixed height */
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05); /* Kept subtle shadow */
    flex-shrink: 0; /* Prevent header from shrinking */
}

.back-button {
    background: none;
    border: none;
    color: white; /* Matched color */
    font-size: 5vw; /* Matched size */
    cursor: pointer;
    padding: 2vw; /* Matched padding */
    margin-left: -2vw; /* Matched margin */
    line-height: 1;
}

.back-button:hover {
    opacity: 0.8; /* Matched hover effect */
}

.header-content {
    text-align: center;
    flex-grow: 1;
}

.header-placeholder {
    width: 10vw; /* Matched placeholder width */
    visibility: hidden;
}

.header-content h1 {
    color: white; /* Matched color */
    font-size: 4.5vw; /* Matched size */
    font-weight: 600;
    margin: 0;
    line-height: 1.3; /* Keep line-height */
}

/* Main Content Area */
.ai-content {
    flex: 1; /* Takes space between buttons and nav bar */
    display: flex;
    flex-direction: column;
    overflow: hidden; /* Prevent this container from scrolling; inner messages will scroll */
    padding: 0 15px 15px 15px; /* 修改：顶部 padding 为 0，保留左右下 */
    z-index: 1; /* Above background */
}

.chat-container {
    flex: 1; /* Fill ai-content */
    display: flex;
    flex-direction: column;
    overflow: hidden; /* Contain children */
    background: white; /* White background for chat */
    border-radius: 16px; /* Rounded corners for chat area */
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05); /* Match LoginView subtle shadow */
}

.messages {
    /* flex: 1; */ 
    flex-grow: 1; 
    flex-shrink: 1; 
    overflow-y: auto; 
    padding: 20px;
    display: flex;
    flex-direction: column;
    gap: 15px;
    /* Adjust 185px based on desired shortness and input area height */
    max-height: calc(100% - 185px); /* Increased subtracted value slightly more */
}

.message {
    display: flex; /* Use flex to align avatar and bubble */
    align-items: flex-start; /* Align items to the top */
    max-width: 85%; /* Adjust max-width slightly */
    gap: 10px; /* Space between avatar and bubble */
}

.message.user {
    align-self: flex-end;
    flex-direction: row-reverse; /* Reverse order for user (bubble, then avatar) */
}

.message.assistant {
    align-self: flex-start;
    /* Default flex-direction: row is fine (avatar, then bubble) */
}

/* Avatar Styles */
.avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: #e9ecef; /* Default background */
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0; /* Prevent avatar from shrinking */
    font-size: 20px; /* Icon size */
    color: #6c757d; /* Default icon color */
}

.message.user .avatar {
    background-color: #4CAF50; /* User avatar background (example green) */
    color: white;
}

.message.assistant .avatar {
    background-color: #2196F3; /* Assistant avatar background (example blue) */
    color: white;
}

.bubble {
    padding: 10px 15px;
    border-radius: 16px;
    font-size: 15px;
    line-height: 1.5;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05); 
    word-wrap: break-word; 
    /* Removed align-self as positioning is handled by message container */
}

.user .bubble {
    background: linear-gradient(135deg, #4CAF50, #2196F3); 
    color: white;
    border-bottom-right-radius: 4px;
}

.assistant .bubble {
    background: #f1f3f5; 
    color: #333; 
    border: none; 
    border-bottom-left-radius: 4px;
}

.loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 15px;
    color: #666; /* Match subtitle color */
    font-size: 13px;
}

.loading-dots {
    display: flex;
    gap: 5px;
    margin-bottom: 8px;
}

.loading-dots span {
    width: 7px;
    height: 7px;
    background-color: #2196F3; /* Use theme blue for dots */
    border-radius: 50%;
    animation: bounce 1.4s infinite ease-in-out both; /* Added 'both' */
}

.loading-dots span:nth-child(1) { animation-delay: -0.32s; }
.loading-dots span:nth-child(2) { animation-delay: -0.16s; }
.loading-dots span:nth-child(3) { animation-delay: 0s; }

@keyframes bounce {
    0%, 80%, 100% { transform: scale(0); }
    40% { transform: scale(1.0); }
}

/* Input Area Styling */
.input-area {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 15px;
    border-top: 1px solid #e9ecef; /* Match LoginView footer border */
    background: #ffffff; /* Ensure white background */
    flex-shrink: 0; /* Ensure input area doesn't shrink */
    min-height: 65px; /* Example min-height */
    /* No position changes needed, it's part of the flex flow */
}

.input-group {
    position: relative;
    flex: 1;
    display: flex; /* Make input group flex */
    align-items: center;
}

.input-icon {
    /* Removed absolute positioning */
    color: #adb5bd; /* Match LoginView input icon color */
    margin-right: 8px; /* Space between icon and input */
    font-size: 18px;
}

.chat-input {
    flex: 1;
    padding: 10px 40px 10px 10px; /* Adjust padding: top/bottom, right (for voice), left */
    border: 1px solid #dee2e6; /* Match LoginView input border */
    border-radius: 10px; /* Match LoginView input radius */
    font-size: 15px;
    outline: none;
    transition: border-color 0.2s, box-shadow 0.2s;
    height: 42px; /* Consistent height */
    box-sizing: border-box;
}

.chat-input:focus {
    border-color: #2196F3; /* Match LoginView focus color */
    box-shadow: 0 0 0 3px rgba(33, 150, 243, 0.1); /* Match LoginView focus shadow */
}

.voice-button {
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
    background: none;
    border: none;
    color: #adb5bd; /* Match LoginView input icon color */
    cursor: pointer;
    padding: 5px;
    font-size: 18px;
    transition: color 0.2s;
}

.voice-button:hover {
    color: #2196F3; /* Use theme blue on hover */
}

.voice-button.active {
    color: #e63946; /* Keep Red for active recording */
    animation: pulse 1.5s infinite ease-in-out;
}

@keyframes pulse {
    0% { opacity: 1; transform: translateY(-50%) scale(1); }
    50% { opacity: 0.7; transform: translateY(-50%) scale(1.1); }
    100% { opacity: 1; transform: translateY(-50%) scale(1); }
}

.send-button {
    width: 42px;
    height: 42px;
    background: linear-gradient(135deg, #4CAF50, #2196F3); /* Match LoginView button gradient */
    border: none;
    border-radius: 50%; /* Keep circular */
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: transform 0.2s, box-shadow 0.2s;
    flex-shrink: 0; /* Prevent shrinking */
    font-size: 18px;
}

.send-button:hover {
    transform: scale(1.05);
    box-shadow: 0 4px 10px rgba(33, 150, 243, 0.2); /* Match LoginView button shadow */
}

.send-button:active {
    transform: scale(0.95);
}

/* 新增：禁用状态下的发送按钮样式 */
.send-button:disabled {
    background: linear-gradient(135deg, #a5d6a7, #90caf9); /* 变暗的颜色 */
    opacity: 0.6; /* 半透明效果 */
    cursor: not-allowed; /* 禁用鼠标指针 */
    box-shadow: none; /* 移除阴影 */
    transform: none; /* 移除悬停或点击时的变换效果 */
}

/* Bottom Nav styles are now handled by the Navigation component */

/* Responsive Adjustments */
@media (max-width: 360px) {
    /* Adjust header padding/sizes if needed for small screens */
    .app-header {
        padding: 3vw; /* Example adjustment */
    }
    .back-button {
        font-size: 6vw; /* Example adjustment */
    }
    .header-content h1 {
        font-size: 5vw; /* Example adjustment */
    }
    .header-placeholder {
        width: 12vw; /* Example adjustment */
    }
    .ai-content {
        padding: 10px;
    }
    .chat-container {
        border-radius: 12px;
    }
    .messages {
        padding: 15px;
        gap: 12px;
    }
    .bubble {
        padding: 8px 12px;
        font-size: 14px;
        border-radius: 14px;
    }
    .input-area {
        padding: 8px 10px;
        gap: 8px;
    }
    .chat-input {
        height: 40px;
        font-size: 14px;
        border-radius: 8px; /* Slightly less rounded on small screens */
    }
    .send-button {
        width: 40px;
        height: 40px;
        font-size: 16px;
    }
    .voice-button {
        font-size: 16px;
    }
}

/* 新增：指标按钮行样式 */
.metric-buttons {
    display: flex;
    justify-content: space-around; /* 或 space-evenly */
    padding: 10px 15px; /* 上下左右内边距 */
    background-color: #ffffff; /* 白色背景 */
    /* border-bottom: 1px solid #e9ecef; */ /* 可选：添加分割线 */
    flex-shrink: 0; /* 防止此行在 flex 布局中被压缩 */
    z-index: 50; /* 确保在背景之上，但在 header 之下（如果 header 有 shadow） */
}

.metric-button {
    padding: 8px 12px;
    border: 1px solid #dee2e6; /* 默认边框颜色，匹配输入框 */
    border-radius: 16px; /* 圆角 */
    background-color: white; /* 默认白色背景 */
    color: #495057; /* 默认文字颜色 */
    font-size: 14px; /* 字体大小 */
    cursor: pointer;
    transition: all 0.3s ease; /* 平滑过渡效果 */
    text-align: center;
    flex-grow: 1; /* 让按钮平均分配空间 */
    margin: 0 5px; /* 按钮之间的间距 */
    max-width: 22%; /* 限制最大宽度 */
}

.metric-button.active {
    background: linear-gradient(135deg, #4CAF50, #2196F3); /* 激活状态背景色 (同 header) */
    color: white; /* 激活状态文字颜色 */
    border-color: transparent; /* 激活状态无边框或使用背景色 */
    font-weight: 600; /* 激活状态加粗 */
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); /* 可选：添加轻微阴影 */
}

.metric-button:not(.active):hover {
    background-color: #f1f3f5; /* 非激活按钮悬停效果 */
    border-color: #adb5bd;
}
</style>